<?php
/**
* Class for "master" models.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\ModelCriteria;
class ScribbleMasterModel extends ScribbleModel {

	/**
	* Return a version.
	*
	* If no release tag is specified, then the latest version will always be
	* returned.
	*
	* If no matching version exists, NULL is returned.
	*
	* @param string Release tag to find
	* @return ScribbleVersionModel|NULL
	*/
	public function findVersion($releaseTag=NULL) {
		$c = new ModelCriteria();
		$c->addOrder('version', 'desc');
		$c->addClause(ModelCriteria::EQUALS, 'releasetag', $releaseTag===NULL ? '' : $releaseTag);
		$matches = $this->findRelatives($this->getVersionModelName(), $c, 'master');
		if($matches->get(0)!==NULL) {
			return $matches->get(0);
		}
		return NULL;
	}

	/**
	* Returns the model name (in UpperCamelCaps notation) used to store versions
	* associated with this master model.
	*
	* By default we assume this to simply be the master model name suffixed with
	* "Version", eg. "Page" -> "PageVersion"
	*
	* @return string
	*/
	public function getVersionModelName() {
		return "{$this->modelName}Version";
	}

	/**
	* Determine if this model has expired.
	*
	* @return bool
	*/
	public function hasExpired($time=NULL) {
		$time = $time===NULL ? time() : $time;
		return $this->dateexpire>0 && $this->dateexpire<=$time;
	}

	/**
	* Determine if this model is published.
	*
	* @return bool
	*/
	public function isPublished($time=NULL) {
		$time = $time===NULL ? time() : $time;
		return !$this->hasExpired() && $this->datepublish>0 && $this->datepublish<=$time;
	}
}
?>